
const http = require('http');
const httpProxy = require('http-proxy');
class Nginx {
    constructor() {
        this.proxySrv = null;
        this.httpSrv = null;
    }

    async init() {
        this.proxySrv = httpProxy.createProxyServer();

        this.httpSrv = http.createServer((req, res) => {

            let urlParts = req.url.toString().split('/');
            console.log("urlParts = ", urlParts);
            // let clientIp = req.connection.remoteAddress.slice(7);
            if(instance.ini.Nginx[urlParts[1]]) {
                instance.log.debug('发送给',urlParts[1]);
                this.forwardReq(req, res,instance.ini.Nginx[urlParts[1]]);
            } else {
                instance.log.debug("检测到默认的请求，发送给",instance.ini.main.default || 'http://127.0.0.1:3000');
                this.forwardReq(req, res,instance.ini.main.default || 'http://127.0.0.1:3000');
            }
        });

        let promise = new Promise((resolve, reject) => {
            this.httpSrv.listen(instance.ini.main.port, () => {
                console.log(`server listening at port ${instance.ini.main.port}`);
                resolve();
            });
        });

        await promise;

    }

    forwardReq(req, res, target) {
        //tools.debug('---- forward to -----', target);
        this.proxySrv.web(req, res, { target: target }, (err) => {
            console.log('error happen ---', err);
            //报错就给应答
            this.writeResBody(res,{code:err?.code||500},500);
        });
    }


    getReqBodyData(req) {
        return new Promise((resolve, reject) => {
            let data = '';
            req.on('data', function (chunk) {
                data += chunk
            });
            req.on('end', function () {
                var reqObj = JSON.parse(data);
                resolve(reqObj);
            });
            req.on('error', (err) => {
                reject(err);
            })
        });

    }

    writeResBody(res, data,code) {
        let statusCode = code;

        res.writeHead(statusCode);
        res.end(JSON.stringify(data));
    }


}

module.exports = Nginx;